import api from './api';
import { products as mockProducts } from '../mock/data';

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  stock: number;
  imageUrl: string;
  category: string;
  createdAt: string;
  updatedAt: string;
}

export interface ProductListResponse {
  products: Product[];
  total: number;
  page: number;
  pageSize: number;
}

export interface ProductQueryParams {
  page?: number;
  pageSize?: number;
  category?: string;
  keyword?: string;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

// Mock implementation using local data
export const getProducts = async (params: ProductQueryParams = {}): Promise<ProductListResponse> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 500));
  
  const { page = 1, pageSize = 10, category, keyword } = params;
  
  // Filter products based on category and keyword
  let filteredProducts = [...mockProducts];
  
  if (category) {
    filteredProducts = filteredProducts.filter(product => product.category === category);
  }
  
  if (keyword) {
    const lowerKeyword = keyword.toLowerCase();
    filteredProducts = filteredProducts.filter(
      product => 
        product.name.toLowerCase().includes(lowerKeyword) || 
        product.description.toLowerCase().includes(lowerKeyword)
    );
  }
  
  // Calculate pagination
  const total = filteredProducts.length;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
  
  return {
    products: paginatedProducts,
    total,
    page,
    pageSize,
  };
};

export const getProductById = async (id: number): Promise<Product> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 300));
  
  const product = mockProducts.find(p => p.id === id);
  
  if (!product) {
    throw new Error('Product not found');
  }
  
  return product;
};

export const getProductsByCategory = async (category: string, params: ProductQueryParams = {}): Promise<ProductListResponse> => {
  return getProducts({ ...params, category });
}; 